<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 公众号服务器配置
 * @author chaituan@126.com
 */
use EasyWeChat\Foundation\Application;
class Notify extends CI_Controller {

	public function index() {
		$options = ['app_id'=>WX_APPID,'secret'=>WX_APPSecret,'token'  => 'ctfanqie'];
		$app = new Application($options);
		$server = $app->server;
		$server->setMessageHandler(function($message) use ($app){
			$content = '';
			switch ($message->MsgType) {
				case 'event':
					$openid = $message->FromUserName;
					$pid = str_replace ('qrscene_', '', $message->EventKey ); // 二维码中的key
					if (strstr($pid,'last_trade_no'))$pid = 0; // 二维码中的key
					$this->load->model("admin/User_model");
					if($message->Event == "subscribe"){
						$user = $this->User_model->get_user('openid',$openid);
						if($user){
							if(!$user['gz']){
								$this->User_model->updates(array('gz'=>1),array('id'=>$user['id']));
							}
							$content = "欢迎回来，亲爱的 {$user['nickname']} 小伙伴";
						}else{
							$userService = $app->user; // 用户
							$wuser = $userService->get($openid)->toArray();
							$username = $this->User_model->fx($wuser,$pid);//添加数据库
							$content = "欢迎您，加入我们，亲爱的 $username 小伙伴";
						}
					}elseif($message->Event == "SCAN"){
						$content = "如果无法访问，请取消在关注";
					}
					break;
				default:
					$content = '';
					break;
			}
			return $content;
		});
		$server->serve()->send();
	}
	
	public function pay(){
		$options = ['app_id'=>WX_APPID,'secret'=>WX_APPSecret,'payment' => ['merchant_id'=> WX_MCHID,'key'=> WX_KEY,'cert_path'=> SSLCERT_PATH,'key_path'=> SSLKEY_PATH,'notify_url'=> NOTIFY_URL]];
		$app = new Application($options);
		$response = $app->payment->handleNotify(function($notify, $successful){
			if($successful){
				$this->load->model(array('admin/User_model','admin/TourismOrder_model','admin/TourismChild_model','admin/Tourism_model','admin/Integral_model'));
				$order_arr = json_decode($notify,true);
				if($order_arr){
					$total = $order_arr['total_fee']/100;
					$order_no = $order_arr['out_trade_no'];
					$time = strtotime($order_arr['time_end']);
					$item = $this->TourismOrder_model->getItem(array('oid'=>$order_no,'state'=>1));
					if($item){
						$where = array('state'=>2,'paytime'=>$time,'wx_oid'=>$order_arr['transaction_id'],'pay_total'=>$total);
						$this->TourismOrder_model->updates($where,array("id"=>$item['id']));
						//减去积分
						if($item['integral']){
							$this->User_model->updates(array('integral'=>'-='.$item['integral']),array('id'=>$item['uid']));
							$this->Integral_model->add(array('uid'=>$item['uid'],'nickname'=>$item['nickname'],'num'=>$item['integral'],'src'=>$item['title'],'ands'=>'-','addtime'=>time()));
						}
						
						$num = count(json_decode($item['info'],true));
						if($item['tcid']){
							//更新子活动
							$this->update_child($item['tcid'], $num);
						}else{//子id没有值的时候 需要创建 子活动
							$stime = $item['stime'];$etime = $item['etime'];$tid = $item['tid'];$uid = $item['uid'];
							//是否该日期已经存在
							$is_child = $this->TourismChild_model->getItem(array("stime"=>$stime),'id');
							if($is_child){//当存在的时候 就不再创建新的活动 执行更新
								$tcid = $is_child['id'];
								$this->update_child($tcid, $num);
							}else{
								$user = $this->User_model->getItems(array('id'=>1),'id,nickname,thumb');
								$tourism = $this->Tourism_model->getItem(array('id'=>$tid),'line_num,in_line,full');
								$leader = json_encode($user);
								$data = array('leader'=>$leader,'uid'=>$item['uid'],'nickname'=>$item['nickname'],'tid'=>$tid,'stime'=>$stime,'etime'=>$etime,'line_num'=>$tourism['line_num'],'in_line'=>$tourism['in_line'],'full'=>$tourism['full'],'sign_num'=>$num+1,'addtime'=>time());
								$tcid = $this->TourismChild_model->add($data);
							}
							if($tcid)$this->TourismOrder_model->updates(array('tcid'=>$tcid,'stime'=>$stime,'etime'=>$etime),array("id"=>$item['id']));
						}
					}else{
						set_Cache($order_no, $order_no);
					}
					return true;
				}else{
					log_message('error', $order_arr['return_msg'].$order_arr['err_code'].$order_arr['err_code_des'].': '.$total.':'.$order_no);
					return false;
				}
			}
		});
		$response->send(); 
		exit();
	}
	
	private function update_child($tcid,$num){
		$this->load->model(array('admin/TourismChild_model'=>'do'));
		$child = $this->do->getItem(array('id'=>$tcid),'sign_num,uid,line_num');
		$edit = array('sign_num'=>"+=$num");
		if($child['uid']){//会员发起 要判断是否要上线
			$total_num = $num + $child['sign_num'];
			if($total_num >= $child['line_num']){//到达指定的数量就执行
				$edit['state'] = 1;
			}
		}
		$this->do->updates($edit,array('id'=>$tcid));
	}
	
	function pay_mall(){
		$options = ['app_id'=>WX_APPID,'secret'=>WX_APPSecret,'payment' => ['merchant_id'=> WX_MCHID,'key'=> WX_KEY,'cert_path'=> SSLCERT_PATH,'key_path'=> SSLKEY_PATH,'notify_url'=> NOTIFY_URL_MALL]];
		$app = new Application($options);
		$response = $app->payment->handleNotify(function($notify, $successful){
			if($successful){
				$this->load->model(array('admin/Order_model'));
				$order_arr = json_decode($notify,true);
				if($order_arr){
					$total = $order_arr['total_fee']/100;
					$order_no = $order_arr['out_trade_no'];
					$time = strtotime($order_arr['time_end']);
					
					$item = $this->Order_model->getItem(array('order_no'=>$order_no,'state'=>1));
					if($item){
						$where = array('state'=>2,'pay_time'=>$time,'transaction_id'=>$order_arr['transaction_id'],'pay_total'=>$total);
						$this->Order_model->updates($where,array("id"=>$item['id']));
					}
					return true;
				}else{
					log_message('error', $order_arr['return_msg'].$order_arr['err_code'].$order_arr['err_code_des'].': '.$total.':'.$order_no);
					return false;
				}
			}
		});
		$response->send();
		exit();
	}
	
}
